<script lang="ts" setup>
import { ref } from 'vue'
import dayjs from 'dayjs'
import BatteryState from '@/components/basic/BatteryState.vue'
import { OptionsArrayType, OptionsData, OptionsType } from '@/types/interface'
import CustomCellGroup from '@/components/basic/Cell/CustomCellGroup.vue'
import { queryBatteryInfo } from '@/api/home'
import { ChargeDischarge } from '@/api/home/index'
import 'vant/es/toast/style'
import {
  ChargeDischargeType,
  chargeSwitchType,
  dischargeSwitchType,
} from '@/api/home/types/home'
import TemperatureImg from '@/assets/temperature.png'
import BatteryImg from '@/assets/battery.png'
import * as echarts from 'echarts'
import {
  batteryAlarmType,
  batteryBasicInfoType,
  batteryHeadType,
} from '@/api/home/types/home'
import { showSuccessToast } from 'vant'
const batteryId = ref<string>('')
const isShow = ref<boolean>(false)
const isLoading = ref<boolean>(false)
const errMsg = ref<string>('暂无数据')
const onSearch = async () => {
  if (!batteryId.value) return
  isLoading.value = true
  const res = await queryBatteryInfo({
    produceId: batteryId.value,
    channel: 'Service',
  })
  if (res.resultCode === 0) {
    now.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
    showBatteryData.value = res.resultData.batteryHead
    showBasicData.value = res.resultData.batteryBasicInfo
    batteryTemperature.value = res.resultData.batteryChart.batteryTemperature
    mosTemperature.value = res.resultData.batteryChart.mosTemperature
    environmentTemperature.value =
      res.resultData.batteryChart.environmentTemperature
    maxMonomerVoltage.value = res.resultData.batteryChart.maxMonomerVoltage
    minMonomerVoltage.value = res.resultData.batteryChart.minMonomerVoltage
    voltageDifference.value = res.resultData.batteryChart.voltageDifference
    voltList.value = res.resultData.batteryChart.voltList
    batteryChartsData.value = res.resultData.batteryChart.getRealtimeDataset
    showAlarmData.value = res.resultData.batteryAlarm
    updateBasicData()
    updateBatteryData()
    updateAlarmData()
    updateVoltageData()
    isShow.value = true
    await initEcharts()
  } else {
    isShow.value = false
    errMsg.value = res.resultMessage
  }

  isLoading.value = false
}
const now = ref<string>(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const showBatteryData = ref<batteryHeadType | null>(null)
const showBasicData = ref<batteryBasicInfoType | null>(null)
const showAlarmData = ref<batteryAlarmType | null>(null)
const BasicData = ref<OptionsData | null>(null)
const BatteryData = ref<OptionsData | null>(null)
const AlarmData = ref<OptionsData | null>(null)
const VoltageData = ref<OptionsData | null>(null)
const VoltageListData = ref<OptionsData | null>(null)
// 电池温度
const batteryTemperature = ref<string>('')
// 功率管温度
const mosTemperature = ref<string>('')
// 箱内温度
const environmentTemperature = ref<string>('')
//最高单体电压
const maxMonomerVoltage = ref<string>('')
// 最低单体电压
const minMonomerVoltage = ref<string>('')
//单体电压压差
const voltageDifference = ref<string>('')
const voltList = ref<string[]>([])
// 动态更新 BatteryData
const updateBatteryData = () => {
  BatteryData.value = [
    {
      type: 'span',
      label: '电池编号',
      value: showBatteryData.value?.batteryNumber,
    },
    [
      {
        type: 'switch',
        label: '充电MOS',
        value: showBatteryData.value?.chargeSwitch,
      },
      {
        type: 'switch',
        label: '放电MOS',
        value: showBatteryData.value?.dischargeSwitch,
      },
    ],
    [
      {
        type: 'tag',
        label: '当前电流',
        value: showBatteryData.value?.electricCurrent + 'A',
        color: '#8DD3B5',
      },
      {
        type: 'tag',
        label: '当前电压',
        value: showBatteryData.value?.voltage + 'V',
        color: '#8DD3B5',
      },
    ],
    [
      {
        type: 'tag',
        label: '当前功率',
        value: showBatteryData.value?.power + 'W',
        color: '#8DD3B5',
      },
      {
        type: 'tag',
        label: '标称容量',
        value: showBatteryData.value?.designCapacity + 'Ah',
        color: '#8DD3B5',
      },
    ],
    [
      {
        type: 'tag',
        label: '剩余容量',
        value: showBatteryData.value?.residualCapacity + 'Ah',
        color: '#8DD3B5',
      },
      {
        type: 'tag',
        label: '循环次数',
        value: showBatteryData.value?.loopCount + '次',
        color: '#8DD3B5',
      },
    ],
  ]
}

// 动态更新 BasicData
const updateBasicData = () => {
  BasicData.value = [
    {
      type: 'span',
      label: '别号',
      value: showBasicData.value?.batteryLockId,
    },
    {
      type: 'span',
      label: 'GPS信号',
      value: showBasicData.value?.gpsStarCount,
    },
    {
      type: 'span',
      label: '经纬度',
      value:
        showBasicData.value?.longtitude + ',' + showBasicData.value?.latitude,
    },
    {
      type: 'span',
      label: 'GPS信号时间',
      value: showBasicData.value?.gpsSignalTime,
    },
    {
      type: 'span',
      label: 'GPS定位时间',
      value: showBasicData.value?.gpsLocateTime,
    },
    {
      type: 'span',
      label: '电池运行时间',
      value: showBasicData.value?.batteryTime,
    },
    [
      {
        type: 'span',
        label: '电池版本',
        value: showBasicData.value?.batteryVersion,
      },
      {
        type: 'tag',
        label: '电池状态',
        value: formatBatteryStatus(showBasicData.value?.batteryStatus),
        color: '#8DD3B5',
        isPlain: true,
      },
    ],
  ]
}
const formatAlarmStatus = (status: string | undefined) => {
  return status === '0' ? '正常' : status === '1' ? '异常' : '未知'
}
const formatAlarmColor = (status: string | undefined) => {
  return status === '0' ? '#8DD3B5' : '#FF676A'
}
const formatBatteryStatus = (status: string | undefined) => {
  return status === '5'
    ? '搁置'
    : status === '3'
      ? '震动'
      : status === '4'
        ? '静止'
        : status === '6'
          ? '移动'
          : ''
}
// 动态更新 BasicData
const updateAlarmData = () => {
  AlarmData.value = [
    [
      {
        type: 'tag',
        label: '均衡告警状态',
        value: formatAlarmStatus(showAlarmData.value?.equilibriumStatus),
        color: formatAlarmColor(showAlarmData.value?.equilibriumStatus),
      },
      {
        type: 'tag',
        label: '电池温度告警',
        value: formatAlarmStatus(showAlarmData.value?.batteryTemperatureStatus),
        color: formatAlarmColor(showAlarmData.value?.batteryTemperatureStatus),
      },
    ],
    [
      {
        type: 'tag',
        label: '电芯过放告警',
        value: formatAlarmStatus(showAlarmData.value?.cellOverDischargeStatus),
        color: formatAlarmColor(showAlarmData.value?.cellOverDischargeStatus),
      },
      {
        type: 'tag',
        label: '总压过放告警',
        value: formatAlarmStatus(
          showAlarmData.value?.voltageOverDischargeStatus,
        ),
        color: formatAlarmColor(
          showAlarmData.value?.voltageOverDischargeStatus,
        ),
      },
    ],
    [
      {
        type: 'tag',
        label: '电芯过压告警',
        value: formatAlarmStatus(showAlarmData.value?.cellOverVoltageStatus),
        color: formatAlarmColor(showAlarmData.value?.cellOverVoltageStatus),
      },
      {
        type: 'tag',
        label: '总压过压告警',
        value: formatAlarmStatus(showAlarmData.value?.voltageOverVoltageStatus),
        color: formatAlarmColor(showAlarmData.value?.voltageOverVoltageStatus),
      },
    ],
    [
      {
        type: 'tag',
        label: '放电过流告警',
        value: formatAlarmStatus(
          showAlarmData.value?.dischargeOverCurrentStatus,
        ),
        color: formatAlarmColor(
          showAlarmData.value?.dischargeOverCurrentStatus,
        ),
      },
      {
        type: 'tag',
        label: '充电过流告警',
        value: formatAlarmStatus(showAlarmData.value?.chargeOverCurrentStatus),
        color: formatAlarmColor(showAlarmData.value?.chargeOverCurrentStatus),
      },
    ],
    [
      {
        type: 'tag',
        label: '放电过温告警',
        value: formatAlarmStatus(
          showAlarmData.value?.dischargeOverTemperatureStatus,
        ),
        color: formatAlarmColor(
          showAlarmData.value?.dischargeOverTemperatureStatus,
        ),
      },
      {
        type: 'tag',
        label: '充电过温告警',
        value: formatAlarmStatus(
          showAlarmData.value?.chargeOverTemperatureStatus,
        ),
        color: formatAlarmColor(
          showAlarmData.value?.chargeOverTemperatureStatus,
        ),
      },
    ],
    [
      {
        type: 'tag',
        label: '环境高温告警',
        value: formatAlarmStatus(
          showAlarmData.value?.environmentHighTemperatureStatus,
        ),
        color: formatAlarmColor(
          showAlarmData.value?.environmentHighTemperatureStatus,
        ),
      },
      {
        type: 'tag',
        label: '环境低温告警',
        value: formatAlarmStatus(
          showAlarmData.value?.environmentLowTemperatureStatus,
        ),
        color: formatAlarmColor(
          showAlarmData.value?.environmentLowTemperatureStatus,
        ),
      },
    ],
    [
      {
        type: 'tag',
        label: 'MOS过温告警',
        value: formatAlarmStatus(showAlarmData.value?.mosTemperatureStatus),
        color: formatAlarmColor(showAlarmData.value?.mosTemperatureStatus),
      },
      {
        type: 'tag',
        label: 'SOC低告警',
        value: formatAlarmStatus(showAlarmData.value?.socLowStatus),
        color: formatAlarmColor(showAlarmData.value?.socLowStatus),
      },
    ],
  ]
}
const formatVoltageList = (list: string[]): OptionsArrayType => {
  const numberList = list.map(item => Number(item))
  const maxMonomerVoltage = Math.max(...numberList)
  const minMonomerVoltage = Math.min(...numberList)
  const maxIndex = numberList.indexOf(maxMonomerVoltage)
  const minIndex = numberList.indexOf(minMonomerVoltage)
  return list.map((item, index) => {
    return {
      type: 'icon',
      label: (index + 1).toString(),
      value: item,
      color:
        index === maxIndex ? '#8DD3B5' : index === minIndex ? '#F89487' : '',
      icon: BatteryImg,
    }
  })
}
const formatColumnVoltageList = (data: OptionsType[]): OptionsArrayType[] => {
  const columnVoltageList: OptionsArrayType[] = []

  for (let i = 0; i < 4; i++) {
    const list = data.slice(i * 4, i * 4 + 4)
    columnVoltageList.push(list)
  }
  return columnVoltageList
}
const updateVoltageData = () => {
  VoltageData.value = [
    [
      {
        type: 'tag',
        label: '最高单体电压',
        value: maxMonomerVoltage.value + 'V',
        color: '#8DD3B5',
        isPlain: true,
      },
      {
        type: 'tag',
        label: '最低单体电压',
        value: minMonomerVoltage.value + 'V',
        color: 'rgba(248, 148, 135, 0.80)',
        isPlain: true,
      },
      {
        type: 'tag',
        label: '单体电压压差',
        color: '#909399 ',
        value: voltageDifference.value + 'V',
        isPlain: true,
      },
    ],
  ]
  const columnVoltageList = formatColumnVoltageList(
    formatVoltageList(voltList.value),
  )
  VoltageListData.value = columnVoltageList
}
/** 最新两小时数据的echarts */
const BatteryCharts = ref<echarts.ECharts | null>(null)
const initEcharts = async () => {
  setTimeout(() => {
    const batteryDom = document.getElementById('latest-data')
    BatteryCharts.value = echarts.init(batteryDom)
    setChartsData()
    window.onresize = () => {
      BatteryCharts.value?.resize({ width: 'auto', height: 'auto' })
    }
  }, 1000)
}
const batteryChartsData = ref<string[][]>([])
const setChartsData = () => {
  const ChartsData: echarts.EChartsCoreOption = {
    dataset: {
      source: batteryChartsData.value,
    },
    color: ['#0DB9BA', '#27EEA0', '#FFCB31'],
    xAxis: {
      type: 'category',
      axisLabel: {
        formatter: function (value: any) {
          return dayjs(value).format('HH:mm')
        },
      },
    },
    legend: {
      top: 0,
      right: 0,
    },
    tooltip: {
      show: true,
      confine: true,
      className: 'tooltip-custom',
      position: 'top',
      formatter: function (params: any) {
        const index = params.encode.y[0]
        const value = params.value[index]
        return `<div class="tooltip-custom-content ${index === 1 ? 'tooltip-0' : index === 2 ? 'tooltip-1' : 'tooltip-2'}">
                <span>${value}</span>
                </div>`
      },
    },
    yAxis: {},
    series: [{ type: 'line' }, { type: 'line' }, { type: 'line' }],
  }
  BatteryCharts.value?.setOption(ChartsData)
}

const handleChange = async (data: OptionsType) => {
  if (data.label !== '充电MOS' && data.label !== '放电MOS') return
  const type = formatChangeType(data)
  const res = await ChargeDischarge({
    produceId: batteryId.value,
    channel: 'Service',
    type,
  })
  if (res.resultCode === 0) {
    showSuccessToast(res.resultMessage)
    if (data.label === '充电MOS') {
      showBatteryData.value!.chargeSwitch = data.value as chargeSwitchType
    } else {
      showBatteryData.value!.dischargeSwitch = data.value as dischargeSwitchType
    }
  }
}
const formatChangeType = (data: OptionsType): ChargeDischargeType => {
  if (data.label === '充电MOS') {
    if (data.value === '1') {
      return 'chargeMosOpen'
    } else {
      return 'chargeMosShut'
    }
  } else {
    if (data.value === '1') {
      return 'dischargeMosOpen'
    } else {
      return 'dischargeMosShut'
    }
  }
}
</script>

<template>
  <div class="app-container">
    <form
      action="
    "
    >
      <van-search
        v-model="batteryId"
        placeholder="请输入电池编号"
        background="var(--xy-white-color)"
        shape="round"
        @search="onSearch"
      />
    </form>
    <div flex flex-col v-if="isShow">
      <div mt-30 pl-30 pr-30 pt-8 pb-8 rounded-10 class="bg-[#F4F5F7]">
        <span class="color-[#333] text-[36px] font-800 leading-60">
          电池信息
        </span>
        <span class="color-grey text-[24px] leading-28 font-200">
          (更新时间: {{ now }})
        </span>
      </div>
      <div
        class="b-1 b-[#EBEEF5] b-solid"
        flex
        flex-col
        items-center
        justify-center
        mt-20
        rounded-10
      >
        <div flex flex-col items-center justify-center>
          <battery-state :-soc="showBatteryData?.soc" mt-50 />
          <div flex items-center w-full mt-36 mb-36>
            <span class="text-[28px] color-black mr-10">SOH:</span>
            <van-progress
              :percentage="showBatteryData?.soh"
              stroke-width="24"
              w-full
              color="#A2CBB3"
            />
          </div>
        </div>
        <div w-full class="cell-group-container">
          <custom-cell-group
            v-for="(item, index) in BatteryData"
            :key="index"
            :data="item"
            @change="handleChange"
          />
        </div>
      </div>
      <div mt-30 pl-30 pr-30 pt-8 pb-8 rounded-10 class="bg-[#F4F5F7]" w-full>
        <span class="color-[#333] text-[36px] font-800 leading-60">
          最新两小时数据
        </span>
      </div>
      <div w-670 h-600 id="latest-data" />
      <div w-full border b-solid b-color="#EBEEF5">
        <van-grid direction="horizontal" :column-num="3">
          <van-grid-item>
            <template #default>
              <div flex items-center>
                <img :src="TemperatureImg" />
                <div flex flex-col class="text-[20px] color-[#333]">
                  <span>箱内温度</span>
                  <span>{{ environmentTemperature }} ℃</span>
                </div>
              </div>
            </template>
          </van-grid-item>
          <van-grid-item>
            <template #default>
              <div flex items-center>
                <img :src="TemperatureImg" />
                <div flex flex-col class="text-[20px] color-[#333]">
                  <span>电池温度</span>
                  <span>{{ batteryTemperature }}℃</span>
                </div>
              </div>
            </template>
          </van-grid-item>
          <van-grid-item>
            <template #default>
              <div flex items-center>
                <img :src="TemperatureImg" />
                <div flex flex-col class="text-[20px] color-[#333]">
                  <span>功率管温度</span>
                  <span>{{ mosTemperature }}℃</span>
                </div>
              </div>
            </template>
          </van-grid-item>
        </van-grid>
        <custom-cell-group
          v-for="(item, index) in VoltageData"
          :key="index"
          :data="item"
        />
        <custom-cell-group
          v-for="(item, index) in VoltageListData"
          :key="index"
          :data="item"
        />
      </div>
      <div mt-30 pl-30 pr-30 pt-8 pb-8 rounded-10 class="bg-[#F4F5F7]" w-full>
        <span class="color-[#333] text-[36px] font-800 leading-60">
          基础信息
        </span>
      </div>
      <div w-full class="cell-group-container" border b-solid b-color="#EBEEF5">
        <custom-cell-group
          v-for="(item, index) in BasicData"
          :key="index"
          :data="item"
        />
      </div>
      <div mt-30 pl-30 pr-30 pt-8 pb-8 rounded-10 class="bg-[#F4F5F7]" w-full>
        <span class="color-[#333] text-[36px] font-800 leading-60">
          报警信息
        </span>
      </div>
      <div w-full class="cell-group-container" border b-solid b-color="#EBEEF5">
        <custom-cell-group
          v-for="(item, index) in AlarmData"
          :key="index"
          :data="item"
        />
      </div>
    </div>
    <div v-else h-500 flex items-center justify-center>
      <span>{{ errMsg }}</span>
    </div>
    <div v-if="isLoading" h-500 flex items-center justify-center>
      <van-loading size="50" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
:deep(
  .cell-group-container .custom-cell-group:last-child .custom-cell:last-child
) {
  .custom-cell-group__content {
    border-radius: 0 0 10px 0px;
    border-bottom: none;
  }
  .custom-cell-group__title {
    border-bottom: none;
  }
}
:deep(
  .cell-group-container .custom-cell-group:last-child .custom-cell:first-child
) {
  .custom-cell-group__title {
    border-radius: 0 0 0 10px;
    border-bottom: none;
  }
  .custom-cell-group__content {
    border-bottom: none;
  }
}
:deep(.tooltip-custom-content) {
  width: 100%;
  height: 100%;
  position: relative;
  background-size: contain;
  > span {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
:deep(.tooltip-1) {
  background-image: url(/src/assets/tooltip-1.png);
  background-repeat: no-repeat;
}
:deep(.tooltip-0) {
  background-image: url(/src/assets/tooltip-0.png);
  background-repeat: no-repeat;
}
:deep(.tooltip-2) {
  background-image: url(/src/assets/tooltip-2.png);
  background-repeat: no-repeat;
}
:deep(.tooltip-custom) {
  padding: 0px !important;
  border: none !important;
  width: 64px;
  height: 64px;
  border-radius: 0 !important;
  box-shadow: none !important;
  display: flex !important;
  justify-content: center;
  align-items: center;
  color: #fff !important;
}
</style>
